package com.skyolder.crutch.ast;

import java.util.ArrayList;

import com.skyolder.crutch.error.GrammarError;
import com.skyolder.crutch.error.RunError;
import com.skyolder.crutch.ev.Environment;
import com.skyolder.crutch.word.BufferTokenPiper;
import com.skyolder.crutch.word.TokenQueue;
import com.skyolder.crutch.word.token.KeyWordToken;
import com.skyolder.crutch.word.token.Token;
import com.skyolder.crutch.word.types.KeyWordType;

public class FileTree implements Tree {
	Environment environment = null;
	TokenQueue tokenQueue = null;
	NameSpaceTree nameSpaceTree=null;
	ArrayList<FunctionTree> trees = new ArrayList<FunctionTree>();
	
	public FileTree(Environment environment, TokenQueue tq) {
		this.environment = environment;
		this.tokenQueue = tq;
	}

	@Override
	public void build() throws GrammarError {
		// TODO Auto-generated method stub
		while (true) {
			Token tk = tokenQueue.peekToken();
			if (tk == null) {
				break;
			}
			if (!(tk instanceof KeyWordToken)) {
				throw new GrammarError(tk.toString());
			}
			KeyWordToken keyWordToken = (KeyWordToken) tk;
			if(keyWordToken.getKeyWordType() == KeyWordType.NAMESPACE){
				NameSpaceTree nameSpaceTree=new NameSpaceTree(environment, tokenQueue);
				nameSpaceTree.build();
				this.nameSpaceTree=nameSpaceTree;
			}
			if (keyWordToken.getKeyWordType() == KeyWordType.FUNCTION) {
				FunctionTree functionTree = new FunctionTree(environment, tokenQueue);
				functionTree.build();
				trees.add(functionTree);
			} else if (keyWordToken.getKeyWordType() == KeyWordType.GLOBAL) {
				GlobalVarTree globalVarTree = new GlobalVarTree(environment, tokenQueue);
				globalVarTree.build();
			} else if (keyWordToken.getKeyWordType() == KeyWordType.INCLUDE) {
				IncludeTree includeTree=new IncludeTree(environment, tokenQueue);
				includeTree.build();
			} else {
				throw new GrammarError(tk.toString());
			}
		}
	}

	public void run(String functionName) throws RunError {
		for (FunctionTree tree : trees) {
			if (tree.getName().equals(functionName)) {
				tree.excute();
				break;
			}
		}
	}

	@Override
	public void excute() {
		// TODO Auto-generated method stub
		for (FunctionTree tree : trees) {
			if (tree.isMain()) {
				tree.excute();
				break;
			}
		}
	}

}
